package com.winning.devops.batch.listener.config;

import com.winning.devops.batch.listener.chunk.FirstChunkExecutionListener;
import com.winning.devops.batch.listener.job.FirstJobExecutionListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.support.ListItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.List;

/**
 * 监听器配置类
 * 配置job、listener
 *
 * @author chensj
 * @date 2020-02-29 15:30
 */
@Configuration
public class ListenerDemoJobConfig {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;
    @Autowired
    private StepBuilderFactory stepBuilderFactory;
    /**
     * logger
     */
    private static final Logger logger = LoggerFactory.getLogger(ListenerDemoJobConfig.class);

    /**
     * 创建一个Job
     *
     * @return job
     */
    @Bean
    public Job firstListenerDemoJob() {
        return jobBuilderFactory
                .get("firstListenerDemoJob")
                .start(firstListenerDemoStep())
                .listener(new FirstJobExecutionListener())
                .build();
    }

    /**
     * 创建一个step
     *
     * @return step
     */
    @Bean
    public Step firstListenerDemoStep() {
        return stepBuilderFactory.get("firstListenerDemoStep")
                // chunkSize 每进行多少次操作，处理一次 read/write/process
                // <String,String> 泛型，指定读和写 类型
                .<String, String>chunk(2)
                // 容错处理
                .faultTolerant()
                .listener(new FirstChunkExecutionListener())
                // 读数据
                .reader(read())
                // 输出
                .writer(write())
                .build();


    }

    /**
     * 写数据操作
     *
     * @return writer
     */
    private ItemWriter<String> write() {
        return new ItemWriter<String>() {
            @Override
            public void write(List<? extends String> list) throws Exception {
                logger.info("ItemWriter write data , current data size {}", list.size());
                for (String s : list) {
                    logger.info("current data: {}", s);
                }
            }
        };
    }

    /**
     * 都数据操作
     *
     * @return reader
     */
    private ItemReader<String> read() {
        return new ListItemReader<>(Arrays.asList("java", "spring", "mybatis", "hibernate", "jpa", "apollo", "jenkins"
        ));
    }

}
